# Greg Johnston
#  <greg.johnston@gmail.com>
#  coolrunning.py
#  Allows us to import a Coolrunning-formatted (CSV) log into Ritual

from csv import DictReader
from log import RitualLog
from calc import *

class CoolRunningDialect():
	delimiter = '\t'

class CoolRunningLog(RitualLog):
	"""This class is formatted like a RitualLog but allows conversion from Coolrunning's format"""
	def __init__(self, origfile):
		self.log = {}
		self.courses = {}
		self.original = self.readlog(origfile)
		self.log = self.importlog()[0]
		self.courses = self.importlog()[1]

	# Import functions
	def readlog(self, file):
		"""Reads a Coolrunning log"""
		f = open(file, "rt")
		fields = ("DATE (M/D/YEAR)", "TIME OF DAY (24-HOUR FORMAT)", "SPORT",
					"ROUTE", "DISTANCE", "MEASURE", "MILES", "ELAPSED TIME",
					"WORKOUT TYPE", "SHOES", "WEIGHT", "WEATHER", "TEMPERATURE",
					"AVG HEART RATE", "RESTING HEART RATE", "MAX HEART RATE", "COMMENTS")
		lines = []
		try:
			reader = DictReader(f, fields, dialect=CoolRunningDialect)
			for row in reader:
				lines = lines + [row]
		finally:
			f.close()
			return lines

	def importlog(self):
		"""Converts self.original into a Ritual-format log, returns result as a tuple of (log, courses)"""
		tmplog = {}
		tmpcourses = {}
		for entry in self.original[1:]: # first row is headers
			if entry["SPORT"] == "Running":
				# do the courses
				if entry["ROUTE"] != None:
					tmpcourses[unescape(entry["ROUTE"])] = (unescape(entry["DISTANCE"]), unescape(entry["MEASURE"]))
				# get the log now
					self.add_entry(string_date(unescape(entry["DATE (M/D/YEAR)"])),
									unescape(entry["ROUTE"]),
									round(float(entry["DISTANCE"]), 1),
									unit_code(entry["MEASURE"]),
									time_in_seconds(entry["ELAPSED TIME"]),
									unescape(entry["SHOES"]),
									unescape(entry["COMMENTS"]))
		return (tmplog, tmpcourses)
